/**
 * axios封装
 * 请求拦截、响应拦截、错误统一处理
 */
import axios from 'axios'
import router from '../router'
// import store from '../store/index'
import { Toast } from 'vant'
import qs from 'qs'
// axios.defaults.withCredentials = false
const baseUrl = process.env.BASE_API
// eslint-disable-next-line valid-jsdoc
/**
 * 提示函数
 * 禁止点击蒙层、显示一秒后关闭
 */
const tip = msg => {
  Toast({
    message: msg,
    duration: 1000,
    forbidClick: true
  })
}






// 创建axios实例
var instance = axios.create({ timeout: 60000 })
// 设置post请求头
// instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
/**
 * 请求拦截器
 * 每次请求前，如果存在token则在请求头中携带token
 */

instance.interceptors.request.use(
  config => {
        let orgId = localStorage.getItem('orgId')
        let userId = localStorage.getItem('userId')
        let params = {}
        // let headerParams = {}
        if (config.method.toLowerCase() == 'post') {

          if (config.data) {
            if (config.data.extype == 1) {
              config.data = {
                name:config.data.name,
                carNo:config.data.carNo
              }
            } else {
              params = config.data
            }
            }

        } else if (config.method.toLowerCase() == 'get') {
          params = {...config.params}
        }

        // if(params && params.headers){
        //   headerParams = params.headers
        //     delete params.headers
        // }
        let token = {satoken:localStorage.getItem('token')}

        config.headers['Content-Type'] = 'application/json;charset=UTF-8';
        // config.headers["Access-Control-Allow-Origin"]= "*";
        if(localStorage.getItem('token')){
          config.headers = Object.assign({}, config.headers,token);
        }
        return config
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
)

// 响应拦截器
instance.interceptors.response.use(
  // 请求成功
  response => {
    // if ((!localStorage.getItem('UserId') || localStorage.getItem('UserId') == '') && goLogin) {
    //   getUserId()
    // }
    if (response.data.code==500) {
      // 需要登录，且还没登录的存储已登录状态
      Toast(response.data.msg)
    }

    if (!response.data.success) {
      return response.data
    }
    if (response && response.data && response.data.data && response.data.data.code != 1) {
      // console.log('错误日志:', response.data);
      return response.data.data
    }

    return response.data.data
  },
  // 请求失败
  error => {
    if (error) {
      // console.log(error, '错误代码')
      if (error.response) {
        // errorHandle(error.response.code, error.response.data)
      }
      return Promise.reject(error)
    } else {
      // 处理断网的情况
      // eg:请求超时或断网时，更新state的network状态
    }
  })

export default instance
